import React, { Component, PropTypes } from 'react';
import ItemTypes from '../../PreviewTool/ItemTypes';
import { DragSource } from 'react-dnd';
import {addItem,closeSystemDialog} from '../../../actions/index';
import Dialog from 'qnui/lib/dialog';

const cardSource = {
  beginDrag(props) {
    return {
		id:1 //工具栏拖出来的预览始终是id为1的占位符。
    };
  },

  endDrag(props, monitor) {
	let re = monitor.getDropResult();
	let count = 0;
	props.dataSource.map(comp=>{
		if(comp.code==props.code){
			count++;
		}
	});
	if(count>=props.maxCount){
		Dialog.alert({content:"本插件最多添加"+props.maxCount+"个"});
		return;
	}
	if(props.dataSource.length>22){
		Dialog.alert({content:"一个页面最多添加20个组件，不能再添加了！"});
		return;
	}
    if(re!=null){
		const param = Object.assign({},props,{
			preview:<props.preview  dataId={props.dataSource[0].maxId+1} />
        });
		props.dispatch(addItem(param,props.dataSource[0].pageId,"new_comp"));
	}
  }
};

@DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging()
}))
export default class ToolItemBase extends Component {
  static propTypes = {
    connectDragSource: PropTypes.func.isRequired,
    isDragging: PropTypes.bool.isRequired,
  };
  render() {
    const { text, isDragging, connectDragSource } = this.props;
	const { name,toolTitle,icon,dataSource,code } = this.props;
    const opacity = isDragging ? 0.4 : 1;
	let count = 0;
		dataSource.map(comp=>{
			if(comp.code==code){
				count++;
			}
		});
	let badge = "";
	if(count===0 ){
		if(this.props.badge){
			badge = <div className="badge">{this.props.badge}</div>;
		}
	}else{
		badge = <div className="badge">{count}</div>;
	}
    return connectDragSource(
      <div className='todomvc-list tool-item' style={{ opacity }}>
		{badge}
        {icon}
		<div className="tool-text">{toolTitle}</div>
      </div>
    );
  }
}